package com.zlmlive.sql.vo;

import org.apache.log4j.Logger;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.zlmlive.sql.SqlParser;
import com.zlmlive.sql.SqlVo;
import com.zlmlive.sql.condition.WhereCondition;
import com.zlmlive.sql.exception.SqlParseException;

/**
 * <pre>
 * 支持删除语法：
 * 
 * DELETE FROM tbl_name
 *  [WHERE where_definition]
 * </pre>
 * @author Min
 *
 */
public class DeleteVo implements SqlVo {

	private static Logger log = Logger.getLogger(DeleteVo.class);

	private String table;

	private WhereCondition condition;

	public void setTable(String table) {
		this.table = table;
	}

	public void setCondition(WhereCondition condition) {
		this.condition = condition;
	}

	@Override
	public String getTable() {
		return this.table;
	}

	public void check() {
		if (null == table || 0 == table.length()) {
			throw new SqlParseException("delete [table] is null");
		}
		if (null != condition) {
			condition.check();
		}
	}

	@Override
	public String toSQL() {
		StringBuilder builder = new StringBuilder();
		builder.append(SqlParser.DELETE_MARK);
		builder.append(SqlParser.BLANK_MARK);
		builder.append(this.table);
		if (null != condition) {
			builder.append(SqlParser.BLANK_MARK);
			builder.append(SqlParser.WHERE_MARK);
			builder.append(SqlParser.BLANK_MARK);
			condition.toSQL(builder);
		}
		return builder.toString();
	}

	public int delete(DBCollection collection, WriteConcern writeConcern) {
		DBObject query = new BasicDBObject();
		if (null != condition) {
			this.condition.setQuery(query, null);
		}

		log(query);

		// WriteResult result = collection.remove(query, WriteConcern.ACKNOWLEDGED);
		WriteResult result = collection.remove(query, writeConcern);
		// collection.remove(query)
		return result.getN();
	}

	private void log(DBObject query) {
		if (log.isInfoEnabled()) {
			StringBuffer sql = new StringBuffer();
			sql.append("db.");
			sql.append(table);
			sql.append(".remove(");

			if (null != query) {
				sql.append(query.toString());
			}
			sql.append(")");
			log.info(sql.toString());
		}
	}
}
